import type { ErrorResponse } from "@/types/response";
import type { AxiosError } from "axios";
import { useTranslation } from "react-i18next";

/**
 * 错误类型
 */
export type ErrorType = "success" | "warning" | "error";

/**
 * 错误类型常量
 */
export const ErrorType = {
  SUCCESS: "success" as ErrorType,
  WARNING: "warning" as ErrorType,
  ERROR: "error" as ErrorType,
};

/**
 * 错误处理结果
 */
export interface ErrorResult {
  message: string;
  type: ErrorType;
}

/**
 * 错误处理工具函数
 */
export class ErrorHandler {
  private t: (key: string) => string;

  constructor(t: (key: string) => string) {
    this.t = t;
  }

  /**
   * 处理 Axios 错误
   */
  handleAxiosError(error: AxiosError<ErrorResponse, unknown>): ErrorResult {
    let errorMessage = this.t(
      "An unexpected error occurred. Please check your network connection and try again."
    );
    let errorType = ErrorType.ERROR;

    if (error.response) {
      // 服务器返回了错误状态码 (4xx, 5xx)
      const responseData = error.response.data;
      if (responseData && responseData.message) {
        // 直接使用服务器返回的错误信息
        errorMessage = responseData.message;
        // 根据状态码确定错误类型
        errorType = this.getErrorType(error.response.status);
      } else {
        // 如果没有具体的错误信息，使用状态码对应的默认信息
        errorMessage = this.getDefaultErrorMessage(error.response.status);
        errorType = this.getErrorType(error.response.status);
      }
    }

    return { message: errorMessage, type: errorType };
  }

  /**
   * 根据 HTTP 状态码确定错误类型
   */
  private getErrorType(status: number): ErrorType {
    if (status >= 400 && status < 500) {
      return ErrorType.WARNING; // 客户端错误使用橙色警告
    } else if (status >= 500) {
      return ErrorType.ERROR; // 服务器错误使用红色错误
    }
    return ErrorType.ERROR; // 默认使用红色错误
  }

  /**
   * 根据 HTTP 状态码获取默认错误信息
   */
  private getDefaultErrorMessage(status: number): string {
    switch (status) {
      case 400:
        return this.t("Invalid request parameters");
      case 401:
        return this.t("Unauthorized access");
      case 403:
        return this.t("Access forbidden");
      case 404:
        return this.t("Requested resource not found");
      case 500:
        return this.t("Internal server error");
      default:
        if (status >= 500) {
          return this.t("Internal server error");
        } else {
          return this.t(
            "An error occurred during registration. Please try again."
          );
        }
    }
  }

  /**
   * 处理通用 API 错误
   */
  handleApiError(error: AxiosError<ErrorResponse, unknown>): ErrorResult {
    return this.handleAxiosError(error);
  }
}

/**
 * 创建错误处理器的 Hook
 */
export const useErrorHandler = () => {
  const { t } = useTranslation();
  return new ErrorHandler(t);
};
